﻿myApp.factory('FoodFactory', [function () {
    var menu = [];
    var menuObj = {};

    var insertMenuItem = function (menuItem) {
        menu.push(menuItem);
    }

    var getMenuItems = function () {
        return menu;
    }

    return {
        insertMenuItem: insertMenuItem,
        getMenuItems: getMenuItems
    };
}]);

myApp.factory('ChatFactory', function ($http) {
    var chatMessages = [];

    var insertMessage = function (messageText) {
        chatMessages.push({
            name: 'Nick',
            text: messageText,
            timestamp: new Date()
        });
    }
    
    var getMessages = function (callback) {
        $http.get('https://codercamps-chatapp.firebaseio.com/.json').success(function (data) {
            var delay = 1000;
            for (var i in data) {
                var timeoutCallback = (function (name) {
                            return function () {
                                data[name].id = name;
                                callback(data[name]);
                                //chatMessages.push(data[i]);
                            }
                })(i);
                setTimeout(timeoutCallback, delay += 1000);
            }
        })

        //return chatMessages;
    }

    return {
        insertMessage: insertMessage,
        getMessages: getMessages
    }
});

myApp.controller('HomeController', function ($scope) {

});

myApp.controller('ChatController', function ($scope, ChatFactory) {
    $scope.messages = [];

    ChatFactory.getMessages(function (message) {
        $scope.$apply(function () {
            $scope.messages.push(message);
        })
    });

    $scope.insertMessage = function () {
        ChatFactory.insertMessage($scope.message);
    }
});

myApp.controller('MenuController', ['$scope', 'FoodFactory', function ($scope, FoodFactory) {
    $scope.menuList = FoodFactory.getMenuItems();


    $scope.menuList.sort(function (a, b) {
        if (a < b) {
            return -1 
        }
        else if (a > b) {
            return 1;
        }
        else {
            return 0;
        }
    });

    $scope.addMenu = function () {
        var menu = {};
        menu.lunchMenu = $scope.lunchMenu;
        menu.lunchSize = $scope.lunchSize;
        menu.lunchPrice = $scope.lunchPrice;
        menu.date = new Date();

        FoodFactory.insertMenuItem(menu);
    }
}]);

myApp.controller('SpecialsController', ['$scope', 'FoodFactory', function ($scope, FoodFactory) {
    $scope.menuList = FoodFactory.getMenuItems();
}]);

myApp.directive('ngWriteWhatever', function () {
    return function (scope, element, attrs) {
        var templateElement = $(element);
        var name = templateElement.attr("ng-write-whatever");
        $(element).html(name);
    }
});